<template>
    <div>
        <SelectArea
            homeType="focus"
            :homeInfo="home"
            @on-edit-info="handleUpdateHome"
            @on-change="handleAreaChange"
        />

        <Card class="no-border-card" style="margin-top:24px;">
            <p slot="title">房间信息</p>
            <div class="c-extra-btn-group" slot="extra">
                <Button type="primary"
                    v-if="canUsingBuildingRoom"
                    class="c-extra-btn"
                    @click="handleAddBuilding">
                    新增楼栋
                </Button>
                <Button type="primary"
                    class="c-extra-btn"
                    @click="handleAddFloor">
                    新增楼层
                </Button>
                <Button
                    type="primary"
                    class="c-extra-btn"
                    @click="showAddRoom">
                    新增房间
                </Button>
            </div>

            <Spin fix v-if="loading">加载中...</Spin>
            <div>
                <div :class="['home-create__building__container', { 'is-overflow': isOverflow }]">
                    <div class="home-create__left__arrow" v-show="isOverflow" @click="handleScrollLeft">
                        <Icon type="chevron-left"></Icon>
                    </div>
                    <div class="home-create__right__arrow" v-show="isOverflow" @click="handleScrollRight">
                        <Icon type="chevron-right"></Icon>
                    </div>
                    <div
                        :class="['home-create__building__list', { 'is-overflow': isOverflow }]"
                        :style="'transform:translateX(' + buildListXPosition + 'px)'"
                        v-if="isBuildingRoom"
                        ref="buildingList">
                        <div
                            :class="['home-create__building__item', 'is-close', { 'is-selected': index === currentBuildingIndex }]"
                            v-for="(building, index) in buildings"
                            :key="building.name"
                            @click="handleBuildingChange(index)">
                            <span class="home-create__building__name">{{building.name}}</span>
                            <div class="home-create__building__btns">
                                <a
                                    class="home-create__building__btn"
                                    href="javascript:;"
                                    @click.prevent="handleEditBuildingName(building, index)">
                                    修改
                                </a>
                                <a
                                    class="home-create__building__btn"
                                    href="javascript:;"
                                    @click.prevent="handleDeleteBuilding(building, index)">
                                    删除
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="margin-bottom-20 margin-top-20">
                    <Select v-model="changeFloorModel.floor" style="width:300px">
                        <Option v-for="floor in couldChangeFloors" :key="floor" :value="floor">修改所选楼层为{{floor}}层</Option>
                    </Select>
                    <i-button type="ghost" :loading="editing" @click="handleChangeFloor">房间批量修改楼层</i-button>
                </div>

                <template v-if="buildings[currentBuildingIndex]">
                    <div
                        class="home-create__focus__room__row"
                        v-for="floor in buildings[currentBuildingIndex].floors"
                        :key="floor">

                        <div class="home-create__focus__room__title is-large">
                            {{floor}}层&nbsp;
                            <Icon type="ios-arrow-right"></Icon>
                            <div class="home-create__focus__room__title__tools">
                                <a
                                    class="home-create__building__btn"
                                    href="javascript:;"
                                    @click.prevent="handleEditFloor(floor)">
                                    修改
                                </a>
                                <a
                                    class="home-create__building__btn"
                                    href="javascript:;"
                                    @click.prevent="handleDeleteFloor(floor)">
                                    删除
                                </a>
                            </div>
                        </div>

                        <div class="home-create__focus__room__list">
                            <div
                                class="home-create__focus__room__item__wrap is-long"
                                v-for="(room, roomIndex) in buildings[currentBuildingIndex].rooms[floor]"
                                :key="roomIndex">
                                <div class="home-create__focus__room__edit">
                                    <div class="home-create__focus__room__prepend">
                                        <input type="checkbox" v-model="room.roomSelected">
                                    </div>
                                    <div class="home-create__focus__room__edit__content">
                                        <span>{{room.name}}</span>
                                        <a class="is-append" href="javascript:;" @click="handleRenameRoom(room, floor, roomIndex)">修改</a>
                                    </div>
                                    <div class="home-create__focus__room__append" @click="handleDeleteRoom(room, floor, roomIndex)">
                                        <Icon class="del-room-icon" type="ios-close-empty"></Icon>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </Card>

        <!-- 新增房间Modal -->
        <Modal
            v-model="addRoomModel.visible"
            width="560"
            title="新增房间"
        >
            <Row :gutter="20" class="margin-bottom-10" v-if="isBuildingRoom">
                <i-col span="4" style="padding-top: 8px">所属楼栋</i-col>
                <i-col span="18">
                    <div class="margin-bottom-10">
                        <i-select v-model="addRoomModel.buildingIndex" @on-change="handleBuildingChangeWhenAddRoom">
                            <i-option
                                v-for="(building, buildingIndex) in buildings"
                                :key="buildingIndex"
                                :value="buildingIndex">
                                {{building.name}}
                            </i-option>
                        </i-select>
                    </div>
                </i-col>
            </Row>
            <Row :gutter="20" class="margin-bottom-10">
                <i-col span="4" style="padding-top: 8px">所属楼层</i-col>
                <i-col span="18">
                    <div class="margin-bottom-10">
                        <i-select v-model="addRoomModel.floor">
                            <template v-if="typeof addRoomModel.buildingIndex === 'number'">
                                <i-option
                                    v-for="floor in buildings[addRoomModel.buildingIndex].floors"
                                    :key="floor"
                                    :value="floor">
                                    {{floor}}
                                </i-option>
                            </template>
                        </i-select>
                    </div>
                    <div class="margin-bottom-10" style="font-size:13px">
                        若房源用电公摊设置为按比例分摊，新增房间需设置分摊比例。
                    </div>
                </i-col>
            </Row>
            <Row :gutter="20" class="margin-bottom-10">
                <i-col span="4" style="padding-top: 8px">房间名称</i-col>
                <i-col span="18">
                    <div class="margin-bottom-10">
                        <Input v-model="addRoomModel.roomName" />
                    </div>
                    <div class="margin-bottom-10" style="font-size:13px">
                        1. 房间名不可重复<br/>
                        2. 如果要添加多个房间，可输入多个房间名，房间名以空格隔开。 如: 房间1 房间2
                    </div>
                </i-col>
            </Row>
            <div slot="footer">
                <Button type="text" size="large" :loading="loading" @click="handleCancelAddRoom">取消</Button>
                <Button type="primary" size="large" :loading="loading" @click="handleAddRoom">保存</Button>
            </div>
        </Modal>

    </div>
</template>

<script>
    import omit from 'lodash/omit'
import countBy from 'lodash/countBy'
import flatten from 'lodash/flatten'
import debounce from 'lodash/debounce'
import intersection from 'lodash/intersection'
import { InputNumber } from 'iview'; // eslint-disable-line
    import SelectArea from '../selectArea'
import { http, api } from '@/libs/http'

/**
 * 功能列表
 * 1. 当个房间名字修改 DONE
 * 2. 单个房间删除 DONE
 * 3. 新增楼层 没有api操作 DONE
 * 4. 新增房间 DONE
 * 5. 批量修改楼层(更新楼层下的房间为新楼层) DONE
 * 6. 编辑楼层(更新楼层下的房间为新楼层) DONE
 * 7. 删除楼层(更新楼层下的房间为首层) DONE
 */
export default {
      name: 'edit-focus-home',
      components: {
        SelectArea
      },
      props: {
        home: Object
      },
      data () {
        return {
          isBuildingRoom: false,
          editing: false,
          loading: false,
          submiting: false,
          buildListXPosition: 0,
          areaData: {}, // 地址等信息
          /**
                 * 数据结构: [{ name: string 楼栋名, floors: [] 楼层列表, rooms: { floor: [] } 房间列表 }]
                 */
          buildings: [],
          currentBuildingIndex: 0,
          isOverflow: false,
          addRoomModel: {
            visible: false,
            roomName: '',
            buildingIndex: '',
            floor: '',
            loading: false
          },
          changeFloorModel: {
            /** 目标楼层 */
            floor: ''
          }
        }
      },
      computed: {
        /** 当前楼栋的可选楼层 */
        couldChangeFloors () {
          const building = this.buildings[this.currentBuildingIndex]
          if (!building) return []
          return building.floors
        },
        currentBuildingName () {
          const building = this.buildings[this.currentBuildingIndex]
          if (!building) return ''
          return '当前楼栋:' + building.name
        },
        canUsingBuildingRoom () {
          return this.$store.state.user.hasFaceAccessPermission
        }
      },
      async created () {
        let rooms = await this.fetchRooms()
        if (!rooms) return
        /** 如果没有room_type为3的房间则是旧的集中式 */
        // if (!rooms.some(room => room.room_type === 3)) {
        //     await this.transformOldFoucs(rooms);
        //     rooms = await this.fetchRooms();
        // }
        this.translateRoomToBuildings(rooms)
      },
      mounted () {
        window.addEventListener('resize', this.onResize)
      },
      methods: {
        handleBuildingChangeWhenAddRoom () {
          this.addRoomModel.floor = ''
        },
        handleAddBuilding () {
          if (!this.isBuildingRoom) {
            this.$Modal.confirm({
              title: '提示',
              content: '<div>为保证房源结构的一致性，现有房间默认会放到1栋中。</div><div>注：楼栋名称可以修改。</div>',
              onOk: () => {
                this.doTransformOldFoucs()
              }
            })
          } else {
            this.askForAddBuilding()
          }
        },
        async doTransformOldFoucs () {
          let rooms = flatten(Object.values(this.buildings[0].rooms)).filter(r => !!r.id)
          await this.transformOldFoucs(rooms)
          rooms = await this.fetchRooms()
          this.translateRoomToBuildings(rooms)
        },
        askForAddBuilding () {
          let buildingName = ''
          this.$Modal.confirm({
            render: h => (
              <div style='margin-top:-20px'>
                <h3 class='margin-bottom-20'>新增楼栋</h3>
                <div class="flex flex-align-center margin-bottom-10">
                  <span style='margin-right: 10px'>楼栋名 </span>
                  <i-input
                    style='flex:1'
                    value={buildingName}
                    onInput={val => { buildingName = val } }
                  >
                  </i-input>
                </div>
                <div style="color:#888;font-size:13px">注: 新建楼栋后需要新增楼层和新增房间才会存储到系统中</div>
              </div>
            ),
            onOk: () => {
              if (!this.checkBuildingName(buildingName)) return
              this.buildings.push({
                name: buildingName,
                floors: [ 1 ],
                rooms: {}
              })
              this.$nextTick(() => {
                this.currentBuildingIndex = this.buildings.length - 1
              })
            }
          })
        },
        /** 批量更新房间楼层 */
        async updateRoomsFloor (floor, roomIds) {
          const { home } = this
          const data = {
            rooms: roomIds.map(id => ({ id, floor }))
          }
          await http.req(api.room_update_multiple, [ home.id ], data)
          this.$Modal.remove()
          this.refreshRooms()
        },
        /** 将旧的集中式房源转换为新的集中式结构接口 */
        async transformOldFoucs (rooms) {
          const loading = this.$Message.loading({
            content: '房源数据更新中...',
            duration: 0
          })
          const data = {
            home_id: this.home.id,
            building_name: '1栋',
            room_ids: rooms.filter(r => r.room_type === 1).map(r => r.id)
          }
          await http.req(api.focus_to_building, null, data)
          loading && loading()
        },
        handleEditFloor (floor) {
          let floorName = Number(floor)
          this.$Modal.confirm({
            loading: true,
            render: h => (
              <div class='margin-bottom-20'>
                <div class='margin-bottom-10'>楼层号</div>
                <InputNumber
                  style='width:100%'
                  value={floorName}
                  min={0}
                  max={99}
                  step={1}
                  precision={0}
                  onInput={val => { floorName = val }}
                >
                </InputNumber>
              </div>
            ),
            onOk: () => {
              if (floorName === Number(floor) || !this.checkFloorName(floorName)) {
                this.$Modal.remove()
              } else {
                const building = this.buildings[this.currentBuildingIndex]
                const isEmptyFloor = !building.rooms[floor] || building.rooms[floor].length === 0
                /** 如果没有添加房间, 则前端删除 */
                if (isEmptyFloor) {
                  this.buildings[this.currentBuildingIndex].floors = [ floorName, ...building.floors.filter(f => f !== Number(floor)) ]
                  this.buildings[this.currentBuildingIndex].rooms = { [floorName]: [], ...omit(building.rooms, [ floor ]) }
                  this.$Modal.remove()
                } else {
                  this.editFloor(floorName, Number(floor))
                }
              }
            }
          })
        },
        editFloor (newFloor, oldFloor) {
          const rooms = this.buildings[this.currentBuildingIndex].rooms[oldFloor]
          const roomIds = rooms.map(r => r.id)
          this.updateRoomsFloor(newFloor, roomIds)
        },
        checkFloorName (floor) {
          const floors = this.buildings[this.currentBuildingIndex].floors
          if (!floor) {
            this.$Message.info('请填写楼层名')
            return false
          } else if (floors.includes(floor)) {
            this.$Message.info('楼层已存在')
            return false
          } else if (!/^[\w\u4e00-\u9fa5-]{1,15}$/g.test(floor)) {
            this.$Message.info({
              content: '请使用15位以内的中英文/数字/-连接的组合',
              duration: 4
            })
            return false
          }
          return true
        },
        handleDeleteFloor (floor) {
          const building = this.buildings[this.currentBuildingIndex]
          if (building.floors.length === 1) {
            this.$Message.info('该楼栋只剩一个楼层, 不可删除')
            return
          }
          const isEmptyFloor = !building.rooms[floor] || building.rooms[floor].length === 0
          if (isEmptyFloor) {
            this.buildings[this.currentBuildingIndex].floors = building.floors.filter(f => f !== Number(floor))
            this.buildings[this.currentBuildingIndex].rooms = omit(building.rooms, [ floor ])
          } else {
            this.$Modal.confirm({
              loading: true,
              title: '确认删除楼层?',
              content: '删除楼层后, 该楼层下的房间将会转移到首层中',
              onOk: () => {
                this.deleteFloor(floor)
              }
            })
          }
        },
        deleteFloor (floor) {
          const { buildings, currentBuildingIndex } = this
          const rooms = buildings[currentBuildingIndex].rooms[floor]
          const roomIds = rooms.map(r => r.id)
          const newFloor = buildings[currentBuildingIndex].floors[0]
          this.updateRoomsFloor(newFloor, roomIds)
        },
        handleRenameRoom (room, floor, roomIndex) {
          let roomName = room.name
          this.$Modal.confirm({
            loading: true,
            render: h => (
              <i-input
                value={roomName}
                onInput={val => { roomName = val } }
              >
              </i-input>
            ),
            onOk: () => {
              if (roomName === room.name || !this.checkRoomName(roomName)) {
                this.$Modal.remove()
              } else {
                this.renameRoom(room.id, roomName, floor, roomIndex)
              }
            }
          })
        },
        async renameRoom (roomId, room_name, floor, roomIndex) {
          const res = await http.req(api.room_update, [roomId], { room_name })
          this.$Modal.remove()
          if (res) {
            this.$Message.success('修改成功')
            this.$set(this.buildings[this.currentBuildingIndex].rooms[floor][roomIndex], 'name', room_name)
          }
        },
        handleChangeFloor () {
          const { floor } = this.changeFloorModel
          const roomIds = this.getCurrentBuildingRoom().filter(r => r.roomSelected).map(r => r.id)
          if (!floor || !roomIds.length) {
            this.$Message.info('请选择目标楼层和需要修改的房间')
          } else {
            this.$Modal.confirm({
              title: '提示',
              content: '确认批量更改楼层操作?',
              onOk: () => {
                this.changeFloor(floor, roomIds)
              }
            })
          }
        },
        async changeFloor (floor, roomIds) {
          this.editing = true
          try {
            await this.updateRoomsFloor(floor, roomIds)
          } catch (err) {
            console.log(err)
          } finally {
            this.editing = false
          }
        },
        /** 新增楼层 */
        handleAddFloor () {
          const { buildings, currentBuildingIndex } = this
          const currentBuilding = buildings[currentBuildingIndex]
          let floor = Math.max(...currentBuilding.floors) + 1
          let building = currentBuilding.name
          const canSelectBuilding = this.isBuildingRoom
          this.$Modal.confirm({
            render: h => (
              <div style='margin-top:-20px'>
                <h3 class='margin-bottom-20'>新增楼层</h3>
                {
                  canSelectBuilding &&
                                <div class="flex flex-align-center margin-bottom-20">
                                  <span style='width: 80px;'>所属楼栋</span>
                                  <i-select style='flex:1' value={building} onInput={val => { building = val }}>
                                    {
                                      buildings.map(building => <i-option value={building.name}>{building.name}</i-option>)
                                    }
                                  </i-select>
                                </div>
                }
                <div class="flex flex-align-center margin-bottom-10">
                  <span style='width: 80px;'>房间楼层</span>
                  <InputNumber
                    style='flex:1'
                    value={floor}
                    min={1}
                    max={99}
                    step={1}
                    precision={0}
                    onInput={val => { floor = val }}
                  >
                  </InputNumber>
                </div>
                <div style="color:#888;font-size:13px">注: 新建楼层后再新增房间才会存储到系统中</div>
              </div>
            ),
            onOk: () => {
              const selectedBuildingIndex = buildings.findIndex(b => b.name === building)
              const selectedBuilding = buildings[selectedBuildingIndex]
              if (!selectedBuilding) {
                this.$Message.info('楼栋不存在')
              } else if (!floor) {
                this.$Message.info('请填写楼层')
              } else if (selectedBuilding.floors.includes(floor)) {
                this.$Message.info(`楼层${floor}已存在`)
              } else {
                /** 根据大小判断楼层插入位置 */
                const insertIndex = this.buildings[selectedBuildingIndex].floors.findIndex(f => Number(f) > Number(floor))
                if (insertIndex > -1) {
                  this.buildings[selectedBuildingIndex].floors.splice(insertIndex, 0, floor)
                } else {
                  this.buildings[selectedBuildingIndex].floors.push(floor)
                }
                this.buildings[selectedBuildingIndex].rooms[floor] = []
              }
            }
          })
        },
        /** 新增房间 */
        showAddRoom () {
          this.addRoomModel.buildingIndex = 0
          this.addRoomModel.visible = true
        },
        handleCancelAddRoom () {
          this.addRoomModel.roomName = ''
          this.addRoomModel.floor = ''
          this.addRoomModel.buildingIndex = ''
          this.addRoomModel.visible = false
        },
        /** 返回当前楼栋下的全部房间 */
        getCurrentBuildingRoom (onlyName) {
          const rooms = flatten(Object.values(this.buildings[this.currentBuildingIndex].rooms))
          return onlyName ? rooms.map(r => r.name) : rooms
        },
        checkRoomName (name) {
          const roomExistNames = this.getCurrentBuildingRoom(true)
          if (!name) {
            this.$Message.info('请填写房间名')
            return false
          } else if (roomExistNames.includes(name)) {
            this.$Message.info('房间名已存在')
            return false
          } else if (name === '公区') {
            this.$Message.info('房间名不能为公区')
            return false
          } else if (!/^[\w\u4e00-\u9fa5-]{1,30}$/g.test(name)) {
            this.$Message.info({
              content: '房间名请使用30位以内的中英文/数字/-连接的组合',
              duration: 4
            })
            return false
          } else if (name.length > 15) {
            this.$Message.info('房间名不能超过15个字符')
            return false
          }
          return true
        },
        /** 新增房间前检查信息 */
        handleAddRoom () {
          const { roomName, floor, buildingIndex } = this.addRoomModel
          const name = roomName.trim()
          if (buildingIndex === '') {
            this.$Message.info('请选择楼栋')
          } else if (!floor) {
            this.$Message.info('请选择楼层')
          } else if (!name) {
            this.$Message.info('请填写房间名')
          } else if (!/^[ \w\u4e00-\u9fa5-]+$/g.test(name)) { // 这里要匹配空格
            this.$Message.info({
              content: '房间名请使用中英文/数字/-连接的组合',
              duration: 4
            })
          } else {
            this.addRoom(buildingIndex, name, floor)
          }
        },
        async addRoom (buildingIndex, name, floor) {
          const { buildings } = this
          const building_name = buildings[buildingIndex].name
          const roomNames = flatten(Object.values(buildings[buildingIndex].rooms)).map(r => r.name)
          // 防止使用多个空格
          const names = name.trim().replace(/\s+/g, '&').split('&')
          const countedNames = countBy(names)
          const duplicateNames = Object.keys(countedNames).filter(key => countedNames[key] > 1)
          if (duplicateNames && duplicateNames.length) {
            this.$Message.info({
              content: `房间名 [ ${duplicateNames.join(',')} ] 重复添加`,
              duration: 3
            })
            return
          }
          const sameNames = intersection(roomNames, names)
          if (names.some(n => n === '公区')) {
            this.$Message.info('房间名不能为公区')
          } else if (names.some(n => n.length > 30)) {
            this.$Message.info('房间名不能超过30个字符')
          } else if (sameNames && sameNames.length) {
            this.$Message.info({
              content: `房间名 [ ${sameNames.join(',')} ] 已存在`,
              duration: 3
            })
          } else {
            const submiting = this.$Message.loading({
              content: '提交中...',
              duration: 0
            })
            const floors = [{
              floor_num: floor,
              rooms: names.map(name => ({ name }))
            }]
            const data = this.isBuildingRoom
              ? { building_floor_rooms: [{ building_name, floors }] }
              : { floor_rooms: floors }

            this.addRoomModel.loading = true
            await http.req(api.room_create, [this.home.id], data)
            submiting()
            this.addRoomModel.loading = false
            this.addRoomModel.visible = false
            this.addRoomModel.buildingIndex = ''
            this.addRoomModel.floor = ''
            this.addRoomModel.roomName = ''
            this.refreshRooms()
          }
        },
        async refreshRooms () {
          const newRooms = await this.fetchRooms() // 保证房间有id
          this.translateRoomToBuildings(newRooms, { keepCurrent: true })
        },
        handleDeleteBuilding (building, index) {
          if (this.buildings.length === 1) {
            this.$Message.info('该房源只剩最后一栋, 不可删除')
            return
          }
          const rooms = flatten(Object.values(building.rooms))
          /** 楼栋下没有房间则前端删除 */
          const emptyBuilding = rooms.length === 0
          if (emptyBuilding) {
            this.buildings.splice(index, 1)
            if (this.currentBuildingIndex === index) {
              this.$nextTick(() => {
                this.currentBuildingIndex = 0
              })
            }
            return
          }
          const hasTenant = rooms.some(room => room.leases.length > 0)
          const hasDevice = rooms.some(room => room.devices.length > 0)
          if (hasTenant) {
            this.$Message.info('该楼栋已入住租客, 不可删除')
          } else if (hasDevice) {
            this.$Message.info('该楼栋已绑定设备, 不可删除')
          } else {
            this.$Modal.confirm({
              loading: true,
              title: '确认删除该楼栋?',
              content: '楼栋删除后, 楼栋下的房间也会被删除',
              onOk: () => {
                this.deleteBuilding(building.id)
              }
            })
          }
        },
        async deleteBuilding (id) {
          const res = await http.req(api.building_delete, [id], null)
          this.$Modal.remove()
          if (res) {
            this.$Message.success('楼栋删除成功')
            const buildIndex = this.buildings.findIndex(b => b.id === id)
            this.buildings.splice(buildIndex, 1)
            if (buildIndex === this.currentBuildingIndex) {
              this.$nextTick(() => {
                this.currentBuildingIndex = 0
              })
            }
          }
        },
        async fetchRooms () {
          try {
            this.loading = true
            const rooms = await http.req(api.room_list, [this.home.id], { with_tenant: 1, with_device: 1 })
            if (rooms) return rooms
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
          return false
        },
        translateRoomToBuildings (rooms, { keepCurrent = false } = {}) {
          const isBuildingRoom = rooms.some(room => room.room_type === 3)
          this.isBuildingRoom = isBuildingRoom
          // 找出楼栋和普通房间
          const [ buildings, plainRooms ] = rooms.reduce(([ buildings, plainRooms ], room) => {
            if (room.room_type === 3) {
              buildings.push({ ...room, name: room.room_name, rooms: {}, floors: [] }) // 将楼栋初始化
            } else if (room.room_type === 1) {
              plainRooms.push({ ...room, roomSelected: false })
            }
            return [ buildings, plainRooms ]
          }, [ [], [] ])
          if (!isBuildingRoom) buildings[0] = { id: 'oldVersionFocus', name: '集中式', rooms: {}, floors: [] }
          // 将房间置入楼栋中
          plainRooms.forEach(room => {
            const { floor, room_name } = room
            let building = buildings.find(b => b.id === room.building_id)
            if (!isBuildingRoom) building = buildings[0]
            if (!building) return
            if (!building.rooms[floor]) building.rooms[floor] = []
            building.rooms[floor].push({ name: room_name, ...room })
            if (!building.floors.includes(floor)) building.floors.push(floor)
          })
          if (!keepCurrent) {
            this.currentBuildingIndex = 0
            this.buildListXPosition = 0
          }
          // buildings.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
          this.buildings = buildings
          this.$nextTick(() => {
            this.checkBuildListWith()
          })
        },
        onResize: debounce(function () {
          this.checkBuildListWith()
        }, 200),
        // 显示长度
        buildListClientWith () {
          return this.$refs.buildingList.clientWidth
        },
        // 总长度加hover长度
        buildListScrollWith () {
          return this.$refs.buildingList.scrollWidth + 110
        },
        // 生层房间或resize界面的时候检查楼层界面长度是否超过
        checkBuildListWith () {
          if (!this.isBuildingRoom || !this.$refs.buildingList) return
          this.isOverflow = this.$refs.buildingList.scrollWidth > this.$refs.buildingList.clientWidth
        },
        handleScrollLeft () {
          if (this.buildListXPosition >= 0) this.buildListXPosition = 0
          const scrollWith = Math.floor(this.buildListClientWith() * 0.7)
          if (this.buildListXPosition + scrollWith > 0) {
            this.buildListXPosition = 0
          } else {
            this.buildListXPosition += scrollWith
          }
        },
        handleScrollRight () {
          const scrollWidth = Math.floor(this.buildListClientWith() * 0.7)
          if (Math.abs(this.buildListXPosition - scrollWidth) > this.buildListScrollWith()) {
            this.buildListXPosition = -(this.buildListScrollWith() - 350)
            return
          }
          this.buildListXPosition -= Math.floor(this.buildListClientWith() * 0.7)
        },
        handleBuildingChange (index) {
          this.currentBuildingIndex = index
          this.changeFloorModel.floor = ''
        },
        async handleUpdateHome () {
          if (this.submiting) return
          this.submiting = true
          const submiting = this.$Message.loading({
            content: '提交中...',
            duration: 0
          })
          try {
            const homeData = this.getHomeData()
            const home = await http.req(api.home_update, [this.home.id], homeData)
            if (!home) throw new Error('修改房源失败')
            this.$Message.success('修改成功')
            this.$emit('success')
          } catch (err) {
            console.log(err)
          } finally {
            this.submiting = false
            submiting()
          }
        },
        /** 返回操作房源需要的参数 */
        getHomeData () {
          const { home_name, street, block, area, city, province, doorNumber, branch_id } = this.areaData
          return {
            home_name: home_name,
            home_type: 2,
            street: street,
            block: block,
            district: area,
            city: city,
            province: province,
            country: '中国',
            number: doorNumber,
            description: home_name,
            branch_id: branch_id || 0
          }
        },
        handleAreaChange (data) {
          this.areaData = data
        },
        checkRoomCanDelete (room) {
          const { devices, leases } = room
          if (devices && devices.length) {
            this.$Message.info('该房间已绑定设备, 不可删除')
            return false
          }
          if (leases && leases.length) {
            this.$Message.info('该房间已入住租客, 不可删除')
            return false
          }
          return true
        },
        /**
             * 删除房间
             */
        handleDeleteRoom (room, floor, roomIndex) {
          if (!this.checkRoomCanDelete(room)) return
          this.$Modal.confirm({
            loading: true,
            title: '提示',
            render: () => (
              <div class='margin-top-10'>确认删除房间{room.name}?</div>
            ),
            onOk: () => {
              this.deleteRoom(room.id, floor, roomIndex)
            }
          })
        },
        async deleteRoom (id, floor, roomIndex) {
          const { currentBuildingIndex: index } = this
          const res = await http.req(api.room_del, [ id ], null)
          this.$Modal.remove()
          if (res) {
            this.$Message.success('删除成功')
            this.buildings[index].rooms[floor].splice(roomIndex, 1)
            /** 最后一个房间删除后清除楼层 */
            if (this.buildings[index].rooms[floor].length === 0) {
              this.buildings[index].floors = this.buildings[index].floors.filter(f => f !== floor)
            }
          }
        },
        /**
             * 修改楼栋名称, 包括修改数据库和本地修改
             */
        handleEditBuildingName (building, buildingIndex) {
          let newName = building.name
          this.$Modal.confirm({
            title: '新名称',
            loading: true,
            render: h => {
              return (
                <i-input
                  value={newName}
                  onInput={val => { newName = val }}
                >
                </i-input>
              )
            },
            onOk: () => {
              if (newName === building.name || !this.checkBuildingName(newName)) {
                this.$Modal.remove()
              } else {
                const rooms = flatten(Object.values(building.rooms))
                /** 楼栋下没有房间则前端修改 */
                const emptyBuilding = rooms.length === 0
                if (emptyBuilding) {
                  this.$set(this.buildings[buildingIndex], 'name', newName)
                  this.$Modal.remove()
                } else {
                  this.editBuilding(buildingIndex, building.id, newName)
                }
              }
            }
          })
        },
        async editBuilding (buildingIndex, id, name) {
          const res = await http.req(api.building_edit, [ id ], { building_name: name })
          this.$Modal.remove()
          if (res) {
            this.$Message.success('修改成功')
            this.$set(this.buildings[buildingIndex], 'name', name)
          }
        },
        checkBuildingName (name) {
          const buildingNames = this.buildings.map(b => b.name)
          if (!name) {
            this.$Message.info('请填写楼栋名')
            return false
          } else if (buildingNames.includes(name)) {
            this.$Message.info('楼栋已存在')
            return false
          } else if (!/^[\w\u4e00-\u9fa5-]{1,15}$/g.test(name)) {
            this.$Message.info({
              content: '请使用15位以内的中英文/数字/-连接的组合',
              duration: 4
            })
            return false
          }
          return true
        }
      },
      beforeDestroy () {
        window.removeEventListener('resize', this.onResize)
      }
    }
</script>

<style lang="less">
    @import url('../home');
</style>